package ar.com.ford.it.fullEconomics.persistence.dao;

import java.io.FileNotFoundException;
import java.util.Collection;
import oracle.toplink.expressions.Expression;
import oracle.toplink.expressions.ExpressionBuilder;
import oracle.toplink.queryframework.ReadAllQuery;
import oracle.toplink.sessions.Session;
import oracle.toplink.tools.sessionmanagement.SessionManager;
import ar.com.ford.it.fullEconomics.exception.FullEconomicsException;
import ar.com.ford.it.fullEconomics.persistence.dto.Teesg01Plant;
import ar.com.ford.it.fullEconomics.persistence.dto.Teesr03Agreement;
import ar.com.ford.it.fullEconomics.persistence.dto.Teesr04Agreemitem;
import ar.com.ford.it.fullEconomics.persistence.dto.Teess01Supplier;
import ar.com.ford.it.webengine.persistence.PersistenceUtil;
import com.ford.it.logging.ILogger;
import com.ford.it.logging.LogFactory;
import com.ford.it.persistence.PersistenceException;
import com.ford.it.persistence.Transaction;

public class AgreementItemDao extends Dao {
    private static final String CLASS_NAME = CommodityDao.class.getName();
    private static final ILogger log = LogFactory.getInstance().getLogger(
            CLASS_NAME);

    public void createAgreementItem(Teesr04Agreemitem item)
            throws PersistenceException {

        String METHOD_NAME = "createAgreementItem";
        log.entering(CLASS_NAME, METHOD_NAME);

        Transaction tx = null;

        tx = PersistenceUtil.getTransaction();
        tx.registerInsert(item);

        log.exiting(CLASS_NAME, METHOD_NAME);
    }

    public Teesr04Agreemitem getAgreementItemForUpdate(
                                                       Teesr03Agreement agreement,
                                                       Integer code,
                                                       Teesg01Plant plant)
            throws PersistenceException {

        String METHOD_NAME = "getAgreementItemForUpdate";
        log.entering(CLASS_NAME, METHOD_NAME);

        Teesr04Agreemitem result = null;
        Teesr04Agreemitem pk = new Teesr04Agreemitem();
        pk.setTeesr03Agreement(agreement);
        pk.setEesr04AgritmNumberK(code);
        pk.setEesr04PlantCodeC(plant);
        result = (Teesr04Agreemitem) super.getObjForUpdate(pk);

        log.exiting(CLASS_NAME, METHOD_NAME);
        return result;
    }

    public void deleteAgreementItem(Teesr04Agreemitem item)
            throws PersistenceException {

        String METHOD_NAME = "deleteAgreementItem";
        log.entering(CLASS_NAME, METHOD_NAME);

        Transaction tx = PersistenceUtil.getTransaction();
        if (tx != null) {
            tx.registerDelete(item);
        }

        log.exiting(CLASS_NAME, METHOD_NAME);
    }

    /**
     * Obtiene los agreement items dado un agreement en particular ordenados por
     * linea de vehiculo
     * 
     * @param
     * @return
     * @throws FullEconomicsException
     */
    public Collection<Teesr04Agreemitem> findAgreementItemsOrderByVehicle(
                                                                          Teesr03Agreement teesr03Agreement)
            throws PersistenceException {

        String METHOD_NAME = "findAgreementItemsOrderByVehicle";
        log.entering(CLASS_NAME, METHOD_NAME);

        Collection<Teesr04Agreemitem> resultCol = null;

        Session session = null;

        try {
            session = SessionManager.getManager().getSession(
                    this.getSessionName());
        } catch (FileNotFoundException e) {
            throw new PersistenceException(e);
        }
        ExpressionBuilder builder = new ExpressionBuilder();
        ReadAllQuery query = new ReadAllQuery(Teesr04Agreemitem.class);

        Expression exp = null;

        // comparo el agreement
        exp = builder.get("teesr03Agreement").equal(teesr03Agreement);

        query.addOrdering(builder.get("ncas012VehicleVw").get(
                "cas012VehicleCodeC").descending());

        query.setSelectionCriteria(exp);

        resultCol = (Collection<Teesr04Agreemitem>) session.executeQuery(query);

        log.exiting(CLASS_NAME, METHOD_NAME);
        return resultCol;
    }
    
    
    /**
     * Obtiene los agreement items dado un agreement en particular ordenados por
     * linea de vehiculo
     * 
     * @param
     * @return
     * @throws FullEconomicsException
     */
    public Collection<Teesr04Agreemitem> findAgreementItemHistory(Teess01Supplier supplier)
            throws PersistenceException {

        String METHOD_NAME = "findAgreementItemHistory";
        log.entering(CLASS_NAME, METHOD_NAME);

        Collection<Teesr04Agreemitem> resultCol = null;
        Session session = null;

        try {
            session = SessionManager.getManager().getSession(
                    this.getSessionName());
        } catch (FileNotFoundException e) {
            throw new PersistenceException(e);
        }
        ExpressionBuilder builder = new ExpressionBuilder();
        ReadAllQuery query = new ReadAllQuery(Teesr04Agreemitem.class);

        Expression exp = null;

        // comparo el agreement
        exp = builder.get("teesr03Agreement").get("teess01Supplier").equal(supplier);
        exp = exp.and(builder.get("teesr03Agreement").get("eesr03AgreeSignatureDateY").notNull());

        query.addOrdering(builder.get("eesr04AgritmEffectiveDateY").descending());
        query.setSelectionCriteria(exp);

        resultCol = (Collection<Teesr04Agreemitem>) session.executeQuery(query);

        log.exiting(CLASS_NAME, METHOD_NAME);
        return resultCol;
    }

    /**
     * Obtiene los agreement items anteriores al agreement Item pasado por
     * parametro
     * 
     * @param
     * @return
     * @throws FullEconomicsException
     */
    public Collection<Teesr04Agreemitem> findPrevAgreementItems(
                                                                Teesr04Agreemitem agreemItem)
            throws PersistenceException {

        String METHOD_NAME = "findPrevAgreementItems";
        log.entering(CLASS_NAME, METHOD_NAME);

        Collection<Teesr04Agreemitem> resultCol = null;
        Session session = null;
        try {
            session = SessionManager.getManager().getSession(
                    this.getSessionName());
        } catch (FileNotFoundException e) {
            throw new PersistenceException(e);
        }
        ExpressionBuilder builder = new ExpressionBuilder();
        ReadAllQuery query = new ReadAllQuery(Teesr04Agreemitem.class);

        Expression exp = null;

        // comparo el agreement
        exp = builder.get("teesr03Agreement").get("teess01Supplier").equal(
                agreemItem.getTeesr03Agreement().getTeess01Supplier());
        if (agreemItem.getEesr04AgritmTypeCodeC().equalsIgnoreCase("P"))
            exp = exp.and(builder.get("teesp04Supply").equal(
                    agreemItem.getTeesp04Supply()));
        else if (agreemItem.getEesr04AgritmTypeCodeC().equalsIgnoreCase("C"))
            exp = exp.and(builder.get("teesp02Commodity").equal(
                    agreemItem.getTeesp02Commodity()));
        exp = exp.and(builder.get("eesr04AgritmEffectiveDateY").lessThan(
                agreemItem.getEesr04AgritmEffectiveDateY()));
        exp = exp.and(builder.get("ncas012VehicleVw").equal(agreemItem.getNcas012VehicleVw()));

        query.setSelectionCriteria(exp);

        resultCol = (Collection<Teesr04Agreemitem>) session.executeQuery(query);

        log.exiting(CLASS_NAME, METHOD_NAME);
        return resultCol;
    }
}
